//
//  SINAStuActivityLeaveWordViewController.m
//  sinashebao
//
//  Created by  androidlongs on 2018/1/23.
//  Copyright © 2018年  androidlongs. All rights reserved.
//

#import "SINAStuActivityLeaveWordViewController.h"
#import "SINAStuHomeActivityLeaveTableViewCell.h"
#import "SINAStuHomeActiviLeaveModel.h"
#import "SINACalendarUtils.h"
#import "SINATableviewUtils.h"

@interface SINAStuActivityLeaveWordViewController ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *mainContentTableView;
@property(nonatomic,strong) NSMutableArray *dataList;

@property (weak, nonatomic) IBOutlet UIView *inputUiView;

//留言输入框
@property (weak, nonatomic) IBOutlet UITextField *inputDesTextField;
//提交留言
@property (weak, nonatomic) IBOutlet UILabel *commitMsgLabel;

@property (strong, nonatomic)  UILabel *noDataUiLabel;
//不可发送留言
@property (weak, nonatomic) IBOutlet UILabel *noSendLeavelabel;



@end

@implementation SINAStuActivityLeaveWordViewController

-(UILabel *)noDataUiLabel{
    if (!_noDataUiLabel) {
        _noDataUiLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, mainW, mainH-154)];
        _noDataUiLabel.textAlignment=NSTextAlignmentCenter;
        _noDataUiLabel.text=@"暂无数据";
        _noDataUiLabel.textColor=[UIColor colorWithHexString:@"#878787"];
        _noDataUiLabel.font=[UIFont systemFontOfSize:18];
        _noDataUiLabel.hidden=NO;
    }
    return _noDataUiLabel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    WeakSelf;
    
    self.navigationItem.title=self.model.activityUserName;
    self.view.backgroundColor=[UIColor colorWithHexString:@"#eeeeee"];
    
    
    //注册观察键盘的变化
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(transformView:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    
    //设置完成按钮
    NSInteger activityStartTime = [self.model.activityStartTime integerValue];
    NSInteger activityEndTime = [self.model.activityStopTime integerValue];
    //当前时间
    NSInteger currentTime = [[SINACalendarUtils currentTimeStr] integerValue];
    
    if (currentTime<activityStartTime) {
        DLog(@"活动未开始");
        //活动未开始
        //活动未开始
        self.noSendLeavelabel.text=@"活动中";
        self.noSendLeavelabel.hidden=YES;
        self.inputDesTextField.hidden=NO;
    }else if(currentTime>=activityStartTime&&currentTime<=(activityEndTime)){
        //中
        DLog(@"活动中");
        self.noSendLeavelabel.text=@"活动中";
        self.noSendLeavelabel.hidden=YES;
        self.inputDesTextField.hidden=NO;
       
    }else if(currentTime>=activityEndTime&&currentTime<=(activityEndTime+30*60*1000)){
        //活动结束 以及结束后的半小时
        DLog(@"完成");
        self.noSendLeavelabel.text=@"已完成 不可发送留言";
        self.noSendLeavelabel.hidden=NO;
        self.inputDesTextField.hidden=YES;
       
    }else{
        //超时
        self.noSendLeavelabel.text=@"已超时 不可发送留言";
        self.noSendLeavelabel.hidden=NO;
        self.inputDesTextField.hidden=YES;
        DLog(@"超时");
    }
    
    
    
    UIView *rightView =[[UIView alloc]initWithFrame:CGRectMake(0,0,100,50)];
    UIButton *rightButton =[[UIButton alloc]initWithFrame:CGRectMake(70,10,20,20)];
    [rightButton addTarget:self action:@selector(peopleInfromation) forControlEvents:UIControlEventTouchUpInside];
    [rightView addSubview:rightButton];
    [rightButton setImage:[UIImage imageNamed:@"分享"] forState:UIControlStateNormal];
//    UIBarButtonItem *rightButtonView = [[UIBarButtonItem alloc]initWithCustomView:rightView ];
    //self.navigationItem.rightBarButtonItem=rightButtonView;
    
    [self.view addSubview:self.noDataUiLabel];
    self.mainContentTableView.delegate=self;
    self.mainContentTableView.dataSource=self;
    self.mainContentTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.mainContentTableView.backgroundColor=[UIColor colorWithHexString:@"#eeeeee"];
    self.mainContentTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.mainContentTableView.hidden = YES;
    self.dataList =[[NSMutableArray alloc]init];
//    self.inputDesTextField.delegate=self;
    NSString *userUid =  [[SINACommonUserHelper share] getUserModel].userUid;
    
    for (int i=0; i<0; i++) {
        
        SINAStuHomeActiviLeaveModel *model  =[[SINAStuHomeActiviLeaveModel alloc]init];
        if (i%3==0) {
            model.msgUserUid =userUid;
        }else{
            model.msgUserUid = @"po";
        }
        [self.dataList addObject:model];
    }
    [self.mainContentTableView reloadData];
    
    //下拉刷新
    self.mainContentTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadingNewData)];
    //上拉刷新
    //    self.mainContentTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadingMoreData)];
    
    //自动更改透明度
    self.mainContentTableView.mj_header.automaticallyChangeAlpha = YES;
    
    //进入刷新状态
    //[self.mainContentTableView.mj_header beginRefreshing];
    
    [self.mainContentTableView.mj_header setBackgroundColor:[UIColor colorWithHexString:@"#eeeeee"]];
    [self.mainContentTableView.mj_footer setBackgroundColor:[UIColor colorWithHexString:@"#eeeeee"]];
    
    
    if ([self.model.itemStatue integerValue]==1) {
        self.inputUiView.hidden = NO;
    }else{
        self.inputUiView.hidden = YES;
        self.mainContentTableView.frame=CGRectMake(self.mainContentTableView.frame.origin.x, self.mainContentTableView.frame.origin.y, self.mainContentTableView.frame.size.width, self.mainContentTableView.frame.size.height+CGRectGetHeight(self.inputUiView.frame));
    }
    
    
    [[SINAUiviewClickLiserner alloc]viewClickFunction:self.commitMsgLabel andWithBlick:^(UIView *view) {
        [weakSelf commitDataFunction];
    }];
    
    [[SINAUiviewClickLiserner alloc]viewClickFunction:self.noDataUiLabel andWithBlick:^(UIView *view) {
        [weakSelf loadingLeaveNetData];
    }];
    
   
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^(void){
        [weakSelf loadingLeaveNetData];
    });
}
-(void)peopleInfromation{
    
}
-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden=NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//下拉刷新 
-(void) loadingNewData{
     [self.mainContentTableView.mj_header endRefreshing];
    
    [self loadingLeaveNetData];
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataList.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    SINAStuHomeActivityLeaveTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SINAStuHomeActivityLeaveTableViewCell"];
    
    if (cell == nil) {
        cell= [[[NSBundle mainBundle]loadNibNamed:@"SINAStuHomeActivityLeaveTableViewCell" owner:nil options:nil] firstObject];
        
    }
    
    SINAStuHomeActiviLeaveModel *model = self.dataList[indexPath.row];
    cell.model = model;
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell ;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 72+20;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
//    NSInteger index = indexPath.row;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == self.inputDesTextField) {
        if (self.inputDesTextField.text.length >=50) {
            self.inputDesTextField.text=[self.inputDesTextField.text substringWithRange:NSMakeRange(0, 49)];
        }
    }
    return YES;
    
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField == self.inputDesTextField) {
        //self.usernameTextfield放弃第一响应者，而self.passwordTextfield变为第一响应者
        [self.inputDesTextField resignFirstResponder];
        
    }
    return YES;
}
//添加留言
-(void) commitDataFunction{
    
    [self.view endEditing:YES];
    
    //设置完成按钮
    NSInteger activityStartTime = [self.model.activityStartTime integerValue];
    NSInteger activityEndTime = [self.model.activityStopTime integerValue];
    //当前时间
    NSInteger currentTime = [[SINACalendarUtils currentTimeStr] integerValue];
    
    if (currentTime<activityStartTime) {
       
    }else if(currentTime>=activityStartTime&&currentTime<=(activityEndTime)){
        //中
        
    }else if(currentTime>=activityEndTime&&currentTime<=(activityEndTime+30*60*1000)){
        //活动结束 以及结束后的半小时
        DLog(@"完成");
         [YPXToastView showToastViewWithText:@"活动已完成 不可发送留言" andDuration:2 andParentView:self.view];
        return;
    }else{
        //超时
        [YPXToastView showToastViewWithText:@"活动已超时 不可发送留言" andDuration:2 andParentView:self.view];
        return;
    }
    
    //留言信息
    NSString *leaveDesString=self.inputDesTextField.text;
    if (leaveDesString==nil||[leaveDesString length]<1) {
          [YPXToastView showToastViewWithText:@"请输入留言内容" andDuration:2 andParentView:self.view];
        return;
    }
    
    //提交数据
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    //组队uuid    String organizeuuid
    [dict setObject:self.model.organizeuuidfordetailUid forKey:@"organizeuuid"];
    //留言用户uuid String studentuuid
    [dict setObject:[[SINACommonUserHelper share]getUserModel].userUid forKey:@"studentuuid"];
    //留言内容  String content
    [dict setObject:leaveDesString forKey:@"content"];
    
    NSMutableDictionary *dict2 = [[NSMutableDictionary alloc]init];
    
    [dict2 setObject:[SINAHttpRequestUtils encodeDicParams:dict] forKey:@"sj"];
    
    [self addLeaveDataFunction:dict2];
    
}
//添加留言数据  提交
-(void) addLeaveDataFunction:(NSMutableDictionary*)dict2{
    
    [self startLoading];
    
    WeakSelf;
    [CXAFNHttpRequestUtils httpPostRequest:[NSString stringWithFormat:@"%@%@",baseUrl,stuAddLeaveMessageUrl] withParamters:dict2 success:^(id responseData) {
        
        [weakSelf stopLoading];
        NSString *code = responseData[@"code"];
        
        if ([code isEqualToString:@"1000"]) {
            [YPXToastView showToastViewWithText:@"添加成功" andDuration:2 andCorner:5 andParentView:weakSelf.view];
//            NSDictionary *result = responseData[@"content"];
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC));
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                self.inputDesTextField.text=@"";
                [weakSelf loadingLeaveNetData];
            });
            
        }else{
            NSString *message =responseData[@"message"];
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定"
                                                                 cancleBtn:nil];
            [alertView showXLAlertView];
        }
        
        
        
    } failure:^(NSError *error, NSInteger errCode) {
        DLog(@"加载 失败  %@ ",error.debugDescription);
        [weakSelf stopLoading];
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"添加验证失败" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
    }];
}

//加载留言
-(void)loadingLeaveNetData{
 
    [self startLoading];
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    
    //发起人的组队uuid String organizeuuid
     [dict setObject:self.model.organizeuuidfordetailUid forKey:@"organizeuuid"];
    //页数 默认1 String page
     [dict setObject:@"1" forKey:@"page"];
    //每页显示条数 默认30 String num
     [dict setObject:@"200" forKey:@"num"];

    
    WeakSelf;
    [CXAFNHttpRequestUtils httpGetRequest:[NSString stringWithFormat:@"%@%@",baseUrl,stuGetLeaveMessageListUrl] withParamters:dict success:^(id responseData) {
        NSString *code = responseData[@"code"];
        [weakSelf stopLoading];
        if ([code isEqualToString:@"1000"]) {
            NSMutableArray *resultArray = responseData[@"content"];
            if (resultArray!=nil&&resultArray.count>0) {
                 [weakSelf.dataList removeAllObjects];
                //有数据
                weakSelf.noDataUiLabel.hidden=YES;
                weakSelf.mainContentTableView.hidden=NO;
                
                for(NSInteger i=0;i<resultArray.count;i++){
                    NSDictionary *dic = resultArray[i];
                    SINAStuHomeActiviLeaveModel *model  =[[SINAStuHomeActiviLeaveModel alloc]initWithDict:dic];
                    [weakSelf.dataList addObject:model];
                }
                
                [weakSelf.mainContentTableView reloadData];
                [[SINATableviewUtils alloc]scrollTableToFoot:self.mainContentTableView andWithAnimate:YES];
                
                
            }else{
                
                if (weakSelf.dataList.count==0) {
                    //无数据
                    weakSelf.noDataUiLabel.hidden=NO;
                    weakSelf.mainContentTableView.hidden=YES;
                }
                
                DLog(@"无数据");
            }
            
        }else{
            NSString *message =responseData[@"message"];
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定"
                                                                 cancleBtn:nil];
            [alertView showXLAlertView];
            //无数据
            weakSelf.noDataUiLabel.hidden=NO;
            weakSelf.mainContentTableView.hidden=YES;
            DLog(@"无数据 异常");
        }
    } failure:^(NSError *error, NSInteger errCode) {
        [weakSelf stopLoading];
        DLog(@"加载 失败  %@ ",error.debugDescription);
        //无数据
        self.noDataUiLabel.hidden=NO;
        self.mainContentTableView.hidden=YES;
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"加载数据失败" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
    }];
    
    
    
    
    
}
//键盘回收
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    for(UIView *view in self.view.subviews)
    {
        [view resignFirstResponder];
    }
}

//移动UIView
-(void)transformView:(NSNotification *)aNSNotification
{
    //获取键盘弹出前的Rect
    NSValue *keyBoardBeginBounds=[[aNSNotification userInfo]objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGRect beginRect=[keyBoardBeginBounds CGRectValue];
    
    //获取键盘弹出后的Rect
    NSValue *keyBoardEndBounds=[[aNSNotification userInfo]objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect  endRect=[keyBoardEndBounds CGRectValue];
    
    //获取键盘位置变化前后纵坐标Y的变化值
    CGFloat deltaY=endRect.origin.y-beginRect.origin.y;
    NSLog(@"看看这个变化的Y值:%f",deltaY);
    
    //在0.25s内完成self.view的Frame的变化，等于是给self.view添加一个向上移动deltaY的动画
    [UIView animateWithDuration:0.25f animations:^{
        [self.view setFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y+deltaY, self.view.frame.size.width, self.view.frame.size.height)];
    }];
}

@end
